package com.xuecheng.auth.controller;

import com.xuecheng.api.auth.AuthControllerApi;
import com.xuecheng.auth.service.AuthService;
import com.xuecheng.framework.domain.ucenter.ext.AuthToken;
import com.xuecheng.framework.domain.ucenter.request.LoginRequest;
import com.xuecheng.framework.domain.ucenter.response.AuthCode;
import com.xuecheng.framework.domain.ucenter.response.JwtResult;
import com.xuecheng.framework.domain.ucenter.response.LoginResult;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class AuthController implements AuthControllerApi {
    @Autowired
    private AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private Integer cookieMaxAge;

    /**
     * 用户登录认证
     * @param loginRequest 封装用户登录时提交的参数信息
     * @return
     */
    @Override
    @PostMapping("/userlogin")
    public LoginResult login(LoginRequest loginRequest) {

        if (loginRequest == null) {
            ExceptionCast.cast(CommonCode.FAIL);
        }
        // 校验用户名
        String username = loginRequest.getUsername();
        if (StringUtils.isEmpty(username)) {
            ExceptionCast.cast(AuthCode.AUTH_USERNAME_NONE);
        }
        //校验密码
        String password = loginRequest.getPassword();
        if (StringUtils.isEmpty(password)) {
            ExceptionCast.cast(AuthCode.AUTH_PASSWORD_NONE);
        }
        //校验验证码
        /*String verifycode = loginRequest.getVerifycode();
        if (StringUtils.isEmpty(verifycode)) {
            ExceptionCast.cast(AuthCode.AUTH_VERIFYCODE_NONE);
        }*/
        //调用service
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        //将用户短令牌放入cookie
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            //用户短令牌
        String jti = authToken.getJti();
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", jti, cookieMaxAge, false);
        return new LoginResult(CommonCode.SUCCESS, jti);
    }

    /**
     * 用户退出
     * @return
     */
    @Override
    @PostMapping("/userlogout")
    public ResponseResult logout() {
        // 从cookie中获取用户短令牌
        String jti_token = this.getTokenFormCookie();
        //1. 清楚redis中的令牌信息
        authService.delToken(jti_token);
        //2. 删除cookie, 设置cookie存活时间为0即可
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "uid", "RandomValue", 0, false);
        return ResponseResult.SUCCESS();
    }

    /**
     * 根据cookie查询redis中的jwt令牌, 登录后展示用户信息调用
     * @return
     */
    @Override
    @GetMapping("/userjwt")
    public JwtResult userjwt() {
        //1. 获取cookie中的用户短令牌
        String jti_token = this.getTokenFormCookie();
        //2. 根据用户短令牌到redis中查询对应的jwt令牌
        AuthToken authToken = authService.getUserToken(jti_token);
        if (authToken ==null) {
            return new JwtResult(CommonCode.FAIL, null);
        }
        return new JwtResult(CommonCode.SUCCESS, authToken.getAccess_token());
    }

    /**
     * 从cookie中获取用户短令牌(jti)
     * @return 用户短令牌
     */
    private String getTokenFormCookie(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> cookieMap = CookieUtil.readCookie(request, "uid");
        String jti_token = cookieMap.get("uid");
        return jti_token;
    }
}
